<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use app\admin\model\scanwork\QualityStandard as QualityStandardModel;
use app\admin\model\scanwork\Process;
use app\admin\model\scanwork\Product;
use think\Db;
use think\exception\DbException;
use think\exception\ValidateException;

/**
 * 质检标准管理
 */
class QualityStandard extends Backend
{
    /**
     * QualityStandard模型对象
     * @var \app\admin\model\scanwork\QualityStandard
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new QualityStandardModel;
        $this->view->assign("processList", $this->getProcessList());
        $this->view->assign("productList", $this->getProductList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自定义
     * 如果需要自定义，请复制application/admin/library/traits/Backend.php中对应的方法来修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            // 手动处理参数，避免buildparams()的闭包问题
            $sort = $this->request->get('sort', 'id');
            $order = $this->request->get('order', 'desc');
            $offset = $this->request->get('offset', 0);
            $limit = $this->request->get('limit', 10);
            
            // 构建基础查询条件
            $where = [];
            
            // 处理搜索条件
            $filter = $this->request->get('filter', '{}');
            $filter = json_decode($filter, true);
            if (is_array($filter)) {
                foreach ($filter as $key => $value) {
                    if ($value !== '' && $value !== null) {
                        $where[$key] = ['like', '%' . $value . '%'];
                    }
                }
            }

            $list = $this->model
                ->with(['process', 'product'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id', 'name', 'process_id', 'product_id', 'status', 'createtime', 'updatetime']);
                if ($row->process) {
                    $row->visible(['process']);
                    $row->getRelation('process')->visible(['name']);
                }
                if ($row->product) {
                    $row->visible(['product']);
                    $row->getRelation('product')->visible(['name']);
                }
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (DbException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (DbException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 获取工序列表
     */
    private function getProcessList()
    {
        return Process::where('status', 1)->column('name', 'id');
    }

    /**
     * 获取产品列表
     */
    private function getProductList()
    {
        return Product::where('status', 1)->column('name', 'id');
    }
}
